<?php
namespace common\logic;
use common\models\UserModel;
use common\models\SendRedpacketModel;
//use yii\db\ActiveQuery;
//use yii\db\Expression;

class SendRedpacketLogic extends Logic
{	
	/**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return SendRedpacketModel::find();
    }
    
	//添加红包
	public function AddRedPacket($uid,$total,$nums,$msgs){
		
//		SendRedpacketLogic::instance()->setLogFile(dirname(dirname(__FILE__))."/transfers.txt");//日志地址
//      SendRedpacketLogic::instance()->log('ppp','aaadddd');
        
		//最小红包总额
		$mintotal = 0.01;
		//最大红包总额
    	$maxtotal = 9999;
    	//红包最少次数
    	$totalnum = 100;
    	
    	//1.查看用户是否存在
    	//1-1.查看金额和数量是否合法
    	//2.查看金额和数量是否对的上
    	//3.查看红包的最小值和对最大值   	
		if($uid<=0){
    		return ['error'=>'用户不存在'];
    	}
    	
    	if($total<$mintotal){
    		return ['error'=>'红包最低'.$mintotal.'元起'];
    	}
    	
    	if($total>$maxtotal){
    		return ['error'=>'红包最高不超过'.$maxtotal.'元'];
    	}
    	
    	if($nums<=0){
    		return ['error'=>'红包数量必须超过1个'];
    	}
    	
    	if($nums>$totalnum){
    		return ['error'=>'最多只能发'.$totalnum.'个红包'];
    	}
    	
    	if($total/$nums < 0.01){
    		return ['error'=>'单个红包不能够超过1分钱'];
    	}
    	
    	if(strlen($msgs)>80){
    		return ['error'=>'红包描述过长'];
    	}
    	
    	$user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
        	return ['error'=>'用户不存在'];
        }
		
		$openid = $user->openid;
		list($time1, $time2) = explode(' ', microtime());
        $order_sn = date('YmdHis', $time2) . str_pad(($time1 * 1000000), 7, '0') . str_pad(rand(10000000000, 99999999999), 11, '0');

		
    	$model = new SendRedpacketModel();
    	$model->userid = $uid;
    	$model->total = $total;
    	$model->nums = $nums;
    	$model->curmoney = $total;
    	$model->curnums = 0;
    	$model->sendtime = 0;
    	$model->redurl = '';
    	$model->paystate = 0;
    	$model->order_sn = $order_sn;
    	$model->message = $msgs;
    	
		if ($model->save()) {
        	return ['error'=>'ok','rid'=>$model->rid,'order_sn'=>$order_sn,'total'=>$total,'openid'=>$openid];
        }
		return ['error'=>'添加失败'];
	}
	
	//购买红包返回
	public function BuyBackRedpacket($order_sn){
		
//		SendRedpacketLogic::instance()->setLogFile(dirname(dirname(__FILE__))."/transfers.txt");//日志地址
//      SendRedpacketLogic::instance()->log($order_sn,'aaa');
//		$db = \Yii::$app->db;	
//		$db->createCommand("insert into ph_errorlog(msg)values('".$order_sn."')")->execute();
		
        
		$order = SendRedpacketModel::findOne(['order_sn' => $order_sn]);
        if(empty($order)){
//      	$db->createCommand("insert into ph_errorlog(msg)values('fall no')")->execute();
            return false;
        }

//      $db->createCommand("insert into ph_errorlog(msg)values('run 2...')")->execute();
        
        if (!empty($order) && $order->paystate == 0) {

//          $db->createCommand("insert into ph_errorlog(msg)values('run 3...')")->execute();

            $order->paystate = 1;
            $order->sendtime = time();
            $order->redurl = FRONTEND_URL.'/redpacket/sharepage?rid='.$order_sn;

//          $db->createCommand("insert into ph_errorlog(msg)values('run 4...')")->execute();

            if ($order->save()) {
            	
//          	$db->createCommand("insert into ph_errorlog(msg)values('fall save')")->execute();
	            return true;
	        }
        }
        
        
        
        return false;
	}
	
	protected $log_file;
	
	public function setLogFile($file)
	{
		$this->log_file = $file;
	}
	
	/**
	 * 写日志
	 *
	 * @param $msg 写入的信息
	 * @param $type 日志类型作为查询标示
	 */
	public function log($msg, $type)
	{
		if ($this->log_file) {
			$log = str_replace(array(
				"\r\n",
				"\r",
				"\n"
			), array(
				"",
				"",
				""
			), $msg);
			error_log($type . ' ' . date('Y-m-d H:i:s') . ' ' . json_encode($log,JSON_UNESCAPED_UNICODE) . "\r\n", 3, $this->log_file);
		}
	}
}
?>